package com.luoboduner.moo.tool.ui.dialog.JsonDialog;

import com.formdev.flatlaf.json.Json;
import com.formdev.flatlaf.util.SystemInfo;
import com.intellij.uiDesigner.core.GridConstraints;
import com.intellij.uiDesigner.core.GridLayoutManager;
import com.luoboduner.moo.tool.App;
import com.luoboduner.moo.tool.dao.TJsonVmMapper;
import com.luoboduner.moo.tool.domain.TJsonVm;
import com.luoboduner.moo.tool.ui.component.RTextSyntaxText.RTextSyntaxText;
import com.luoboduner.moo.tool.ui.dialog.JsonVmDialog.JsonVmDialog;
import com.luoboduner.moo.tool.util.ComponentUtil;
import com.luoboduner.moo.tool.util.SystemUtil;
import com.luoboduner.moo.tool.util.vm.VelocityUtitl;
import lombok.Getter;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
/**
 * 一次性将 json 转换为其他格式
 * @author Liutime
 */
@Getter
public class JsonDialog extends JDialog {

  private JPanel contentPane;

  private JTabbedPane tabbedPane1;

  private JLabel tipsLabel;

  private String content;

  /**
   * true 为 VM 模式（根据模板配置 生成）
   * false 为 预览 模式（根据文件类型 预览）
   */
  private boolean type = false;


  /**
   * @param tips
   * @param content
   */
  public JsonDialog(String tips, String content) {
    this(tips, content, false);
  }

  public JsonDialog(String tips, String content, boolean type) {

    super(App.mainFrame, "Result");
    this.content = content;
    this.type = type;
    init();
    ComponentUtil.setPreferSizeAndLocateToCenter(this, 0.6, 0.8);
    setContentPane(contentPane);
        /*
        阻塞父窗口：对话框显示时，用户无法操作父窗口（App.mainFrame），直到对话框关闭。
        典型场景：用于必须完成当前操作才能继续的交互（如确认对话框、数据输入框）。
         */
    setModal(true);

    tipsLabel.setText(tips);

    if (SystemUtil.isMacOs() && SystemInfo.isMacFullWindowContentSupported) {
      this.getRootPane().putClientProperty("apple.awt.fullWindowContent", true);
      this.getRootPane().putClientProperty("apple.awt.transparentTitleBar", true);
      this.getRootPane().putClientProperty("apple.awt.fullscreenable", true);
      this.getRootPane().putClientProperty("apple.awt.windowTitleVisible", false);
      GridLayoutManager gridLayoutManager = (GridLayoutManager) contentPane.getLayout();
      gridLayoutManager.setMargin(new Insets(28, 0, 0, 0));
    }


  }

  /**
   * 初始化选项卡
   */
  public void init() {
    Map<String, KeyValue> map = KeyValue.map;
    Set<String> strings = map.keySet();

    /*
    vm 模式
     */
    if (type) {
      TJsonVmMapper jsonVmMapper = JsonVmDialog.jsonVmMapper;
      List<TJsonVm> tJsonVms = jsonVmMapper.selectAll();
      for (TJsonVm tJsonVm : tJsonVms) {
        String[] name = tJsonVm.getName().split(Pattern.quote("."));
        //TODO this.content 与 vm 结合 后 渲染 也可以缓存起来
        String result = VelocityUtitl.gen(this.content, tJsonVm.getContent(), name[1]);

        /*
        添加选项卡
         */
        RTextSyntaxText json = new RTextSyntaxText(name[1], result);
        JPanel contentPane1 = json.getContentPane();
        tabbedPane1.addTab(name[0], contentPane1);


        /*
        选项卡 切换
         */
        tabbedPane1.addChangeListener(new ChangeListener() {
          @Override
          public void stateChanged(ChangeEvent e) {
            int selectedIndex = tabbedPane1.getSelectedIndex();
            String tabTitle = tabbedPane1.getTitleAt(selectedIndex);
            //TODO 调用完成后可以缓存起来,减少计算速率
            String apply = map.get(tabTitle).getValue().apply(result);

            json.getTextArea().setText(apply);

          }
        });
      }
    } else {
    /*
    预览模式
     */
      for (String s : strings) {

        /*
        添加选项卡
         */
        RTextSyntaxText json = new RTextSyntaxText(s, this.content);
        JPanel contentPane1 = json.getContentPane();
        tabbedPane1.addTab(s, contentPane1);

        /*
        选项卡 切换
         */
        tabbedPane1.addChangeListener(new ChangeListener() {
          @Override
          public void stateChanged(ChangeEvent e) {
            int selectedIndex = tabbedPane1.getSelectedIndex();
            String tabTitle = tabbedPane1.getTitleAt(selectedIndex);
            //TODO 调用完成后可以缓存起来,减少计算速率
            String apply = map.get(tabTitle).getValue().apply(content);

            json.getTextArea().setText(apply);

          }
        });
      }
    }
  }

  {
// GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE!
    $$$setupUI$$$();
  }

  /**
   * Method generated by IntelliJ IDEA GUI Designer
   * >>> IMPORTANT!! <<<
   * DO NOT edit this method OR call it in your code!
   *
   * @noinspection ALL
   */
  private void $$$setupUI$$$() {
    contentPane = new JPanel();
    contentPane.setLayout(new GridLayoutManager(2, 1, new Insets(0, 0, 0, 0), -1, 10));
    contentPane.setEnabled(true);
    contentPane.setMaximumSize(new Dimension(111, 111));
    contentPane.setMinimumSize(new Dimension(41, 111));
    contentPane.setOpaque(false);
    contentPane.setPreferredSize(new Dimension(41, 100));
    contentPane.setRequestFocusEnabled(true);
    tipsLabel = new JLabel();
    tipsLabel.setText("Label");
    contentPane.add(tipsLabel, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
    final JPanel panel1 = new JPanel();
    panel1.setLayout(new GridLayoutManager(1, 1, new Insets(0, 0, 0, 0), -1, -1));
    contentPane.add(panel1, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
    tabbedPane1 = new JTabbedPane();
    panel1.add(tabbedPane1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
  }

  /**
   * @noinspection ALL
   */
  public JComponent $$$getRootComponent$$$() {
    return contentPane;
  }


  private void createUIComponents() {
    // TODO: place custom component creation code here
  }
}
